/**
 * Description:一些注释<br/>
 * CreateTime:2019-03-28<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
package cn.cnsy123.bookwebsiteserver.service.role.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import cn.cnsy123.bookwebsiteserver.constant.CommonConstant;
import cn.cnsy123.bookwebsiteserver.entity.SysUserPrivInfo;
import cn.cnsy123.bookwebsiteserver.entity.SysUserRoleInfo;
import cn.cnsy123.bookwebsiteserver.param.RoleInsertParam;
import cn.cnsy123.bookwebsiteserver.param.RolePrivParam;
import cn.cnsy123.bookwebsiteserver.param.RolePrivRead;
import cn.cnsy123.bookwebsiteserver.param.RoleUpdateParam;
import cn.cnsy123.bookwebsiteserver.repository.SysRoleInfoDao;
import cn.cnsy123.bookwebsiteserver.repository.SysRolePrivInfoDao;
import cn.cnsy123.bookwebsiteserver.service.role.SysRoleInfoService;
import cn.cnsy123.bookwebsiteserver.util.JsonUtil;
import cn.cnsy123.bookwebsiteserver.vo.layui.CommonResult;
import cn.cnsy123.bookwebsiteserver.vo.layui.TableResult;

/**
 * Description:角色信息处理<br/>
 * CreateTime:2019-03-28<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
@Service
public class SysRoleInfoServiceImpl implements SysRoleInfoService {
    
    private static final Logger logger = LoggerFactory.getLogger(SysRoleInfoServiceImpl.class);

    @Autowired
    private SysRoleInfoDao sysRoleInfoDao;
    
    @Autowired
    private SysRolePrivInfoDao sysRolePrivInfoDao;

    @Override
    @Transactional(rollbackFor = RuntimeException.class,readOnly = true)
    public TableResult<SysUserRoleInfo> findRoleInfo(int page,int size) {
        List<SysUserRoleInfo> data = null;
        String msg = "获取数据为空";
        int flag = 1;
        long count = 0L;
        try {
            
            Page<SysUserRoleInfo> pageData = sysRoleInfoDao.findAll(PageRequest.of((page-1), size));
            data = pageData.getContent();
            count = pageData.getTotalElements();
            if(count > 0) {
               msg = "获取数据成功";
               flag = 0;
            }
        } catch (Exception e) {
            logger.error("获取角色信息失败，原因：",e);
            msg = "获取数据出错";
            flag = 1;
            count = 0L;
            data = null;
            throw new RuntimeException("获取角色信息失败");
        }
        TableResult<SysUserRoleInfo> result = new TableResult<SysUserRoleInfo>(flag, msg, count, data);
        logger.info("查询结果:{}",JsonUtil.obj2jsonStr(result));
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> deleteRoleInfo(Long roleId) {
        int code = 1;
        String msg = "";
        try {
            sysRoleInfoDao.deleteById(roleId);
            code = 0;
            msg = "删除成功";
        } catch (Exception e) {
            code = 1;
            msg = "删除出现异常";
            logger.error("删除角色[id="+roleId+"]失败,原因:",e);
            throw new RuntimeException("删除角色[id="+roleId+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> updateRoleInfo(RoleUpdateParam param) {
        int code = 1;
        String msg = "";
        try {
            SysUserRoleInfo entity = sysRoleInfoDao.findByRoleId(param.getRoleId());
            entity.setRoleDesc(param.getRoleDesc());
            entity.setRoleName(param.getRoleName());
            sysRoleInfoDao.saveAndFlush(entity);
            code = 0;
            msg = "修改成功";
        } catch (Exception e) {
            code = 1;
            msg = "修改出现异常";
            logger.error("修改角色[id="+param.getRoleId()+"]失败,原因:",e);
            throw new RuntimeException("修改角色[id="+param.getRoleId()+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> insertRoleInfo(RoleInsertParam param) {
        int code = 1;
        String msg = "";
        try {
            SysUserRoleInfo entity = new SysUserRoleInfo();
            entity.setRoleDesc(param.getRoleDesc());
            entity.setRoleName(param.getRoleName());
            entity.setDeleteFlag(CommonConstant.ENTITY_EXIST);
            entity.setCreateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
            sysRoleInfoDao.saveAndFlush(entity);
            code = 0;
            msg = "新增成功";
        } catch (Exception e) {
            code = 1;
            msg = "新增出现异常";
            logger.error("新增角色[roleName="+param.getRoleName()+"]失败,原因:",e);
            throw new RuntimeException("新增角色[roleName="+param.getRoleName()+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public CommonResult<Object> updateRolePrivInfo(@Valid RolePrivParam param) {
        int code = 1;
        String msg = "";
        try {
            String privResult = param.getPrivResult();
            String [] privItems = privResult.split(",");
            sysRolePrivInfoDao.deleteByRoleId(Long.valueOf(param.getRoleId()));
            for(int i = 0; i< privItems.length; i++) {
                SysUserPrivInfo sysUserPrivInfo = new SysUserPrivInfo(Long.valueOf(param.getRoleId()), privItems[i]);
                sysRolePrivInfoDao.saveAndFlush(sysUserPrivInfo);
            }
            code = 0;
            msg = "权限配置成功";
        } catch (Exception e) {
            code = 1;
            msg = "权限配置出现异常";
            logger.error("权限配置[roleId="+param.getRoleId()+"]失败,原因:",e);
            throw new RuntimeException("权限配置[roleId="+param.getRoleId()+"]失败");
        }
        CommonResult<Object> result = new CommonResult<Object>(code, msg);
        return result;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class,readOnly = true)
    public CommonResult<List<Map<String, String>>> findRolePrivItem(@Valid RolePrivRead param) {
        final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        String msg = "获取数据为空";
        int flag = 1;
        try {
            
            List<SysUserPrivInfo> result = sysRolePrivInfoDao.findAllByRoleId(param.getRoleId());
            
            if(!CollectionUtils.isEmpty(result)) {
                result.stream().forEach(item -> {
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    map.put("pageId", item.getPageId());
                    data.add(map);
                });
               msg = "获取数据成功";
               flag = 0;
            }
        } catch (Exception e) {
            logger.error("获取角色[roleId="+param.getRoleId()+"]权限信息失败，原因：",e);
            msg = "获取数据出错";
            flag = 1;
            throw new RuntimeException("获取角色[roleId="+param.getRoleId()+"]权限信息失败");
        }
        CommonResult<List<Map<String, String>>> result = new CommonResult<List<Map<String, String>>>(flag, msg, data);
        logger.info("查询结果:{}",JsonUtil.obj2jsonStr(result));
        return result;
    }

}
